import { app } from "electron/main";
import { appendFileSync, mkdirSync } from "fs";
import { EOL } from "os";
import { sep, resolve, dirname, join } from "path";
import { isObject } from "@utils/judge";
import { Log_Enum } from "@enum/app.enum";
import { Ipc } from "@main/helper/ipcMain";
import { Ipc_ChannelEnum } from "@enum/channel.enum";

export class Log {
  static get logPath(): string {
    return !app.isPackaged
      ? resolve("logs")
      : join(app.getAppPath(), "../../logs");
  }

  static storageFile(type: Log_Enum, val: string): void {
    const date = new Date();

    //sep 系统文件路径分隔符
    const path =
      this.logPath +
      `${sep}${date.getFullYear()}-${(date.getMonth() + 1)
        .toString()
        .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}.log`;

    //EOL 系统换行符
    const str = `[${date.getHours().toString().padStart(2, "0")}:${date
        .getMinutes()
        .toString()
        .padStart(2, "0")}:${date
        .getSeconds()
        .toString()
        .padStart(2, "0")}] [${type}] ${val}${EOL}`;  
        
        mkdirSync(dirname(path), { recursive: true }); 
        appendFileSync(path, str);

  }

  static writelogs(type: Log_Enum, val: any[]): boolean {

    try {
      let data = "";

      val.forEach((e: any) => {
        if (isObject(e)) data += JSON.stringify(e);
        else data += e.toString();
        data += "\n";
      });

      this.storageFile(type, data);
      return true;
    } catch (error) {
      console.log('日志创建失败：' + error)  
      return false
    }
  }

  static on(): void {
    Ipc.handle<[Log_Enum, any[]]>(
      Ipc_ChannelEnum.APP_WRITE_LOGS,
      (_, ...vals) => {
        return this.writelogs(...vals);
      }
    );
  }
}
